<template>
  <div class="loginBox">
    <div class="right  flex flex-items-center justify-center">
      <div class="flex flex-col flex-items-center">
        <img src="../../assets/icons/logo.svg" style="width: 138px; height: 48px;" />
        <p class="referral ">智慧厨房 ｜ 鸿博引领 ｜ 专注10年 ｜ 不忘初心</p>
        <div class="infoBox">
          备案信息： <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">粤ICP备16078458号</a>
        </div>
      </div>

    </div>
    <div class="left flex flex-col flex-items-center justify-center">
      <div class="left-content">

        <p class="title cmb-16">欢迎登录!</p>
        <p class="sub_title">鸿博智成留样柜后台管理系统</p>

        <el-form ref="loginFormRef" :model="loginForm" label-width="65px" @keyup.enter="login">
          <el-form-item label="账号">
            <el-input v-model.trim="loginForm.loginName" maxlength="20" placeholder="请输入账号">
            </el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model.trim="loginForm.password" maxlength="20" show-password placeholder="请输入密码"
              type="password">
            </el-input>
          </el-form-item>
        </el-form>

        <cusButton color="#0052D9" @click="login" CssObj="width:375px;height:56px"
          :disabled="!(loginForm.loginName && loginForm.password)">登录</cusButton>

      </div>
      <p class="cmt-16 version">版本号：Ks.v1.01.sample.F</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  useRouter,
  LocationQueryValue,
  LocationQuery,
  useRoute,
} from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { getLogin, reqUserinfo, reqLogout } from "@/api/business/user";
import { LoginData } from "@/api/business/user/types";
import { reqMultiRoles } from "@/api/business/menu";

const userStore = useUserStore();

const permissionStore = usePermissionStoreHook();
const router = useRouter();
const route = useRoute();

// 用户信息表单
const formOrigin = () => ({
  loginName: "",
  password: "",
});

const loginForm = ref<LoginData>(formOrigin());
const loginFormRef = ref(null);


const login = () => {
  if (loginForm.value.loginName && loginForm.value.password) {
    userStore.login(loginForm.value).then(async (res) => {
      const rolesList = await userStore.getUserInfo();
      const accessRoutes = await permissionStore.generateRoutes(rolesList);
      accessRoutes.forEach((route) => {
        router.addRoute(route);
      });
      ElMessage.success("登录成功");
      const query: LocationQuery = route.query;
      const redirect = (query.redirect as LocationQueryValue) ?? "/";
      const otherQueryParams = Object.keys(query).reduce(
        (acc: any, cur: string) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        },
        {}
      );
      router.push({ path: redirect, query: otherQueryParams });

    });
  } else {
    ElMessage.info("请完善登录信息");
  }
};

// const login = () => {
//   if (loginForm.value.loginName && loginForm.value.password) {
//     getLogin(loginForm.value).then(res => {
//       if (res.code == 1) {
//         userStore.setToken(res.data.token)
//         getUserInfo().then(roles => {
//           generateRoutes(roles)
//         })
//       } else {
//         ElMessage.error(res.msg);
//       }
//     })
//   } else {
//     ElMessage.info("请完善登录信息");
//   }
// }

// 获取信息(用户昵称、头像、角色集合、路由信息集合)
const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    reqUserinfo().then(async (res) => {
      if (res.code == 1) {
        userStore.setUserInfo(res.data);
        const rolesList = res.data.role.map((el) => el.id);
        resolve(rolesList)
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}
// 接口获取所有路由
const generateRoutes = (roles: []) => {
  reqMultiRoles({ roles }).then((res) => {
    if (res.code == 1) {
      const accessedRoutes = permissionStore.filterAsyncRoutes(res.data);
      permissionStore.setRoutes(accessedRoutes);
      accessedRoutes.forEach((route) => {
        router.addRoute(route);
      });
      ElMessage.success("登录成功");
      const query: LocationQuery = route.query;
      const redirect = (query.redirect as LocationQueryValue) ?? "/";
      const otherQueryParams = Object.keys(query).reduce(
        (acc: any, cur: string) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        },
        {}
      );
      router.push({ path: redirect, query: otherQueryParams });
      console.log(router.getRoutes())
      // 根据角色获取有访问权限的路由
    } else {
      ElMessage.error(res.msg);
    }
  });
}

</script>

<style lang="scss" scoped>
::v-deep .el-input__wrapper {
  box-shadow: none;
}

.el-form-item--default {
  padding: 10px 0;
  border-bottom: 1px solid #dcdde1;
  // margin: 0;
}

::v-deep .el-form-item__label {
  justify-content: flex-start;
}

.loginBox {
  display: flex;
  width: 100%;
  height: 100%;
  font-family: PingFang SC;

  .right {
    width: 60%;
    height: 100%;
    background: linear-gradient(135deg, #366ef4, #0052d9);
    position: relative;

    &::after {
      content: "";
      position: absolute;
      height: 550px;
      width: 100%;
      bottom: 0;
      background: url("@/assets/images/login-bg.png") no-repeat;
      background-size: cover;
      opacity: 0.4;
    }
  }

  .left {
    flex: 1;
    height: 100%;

    &-contnet {
      width: 375px;
    }

    .el-form {
      margin: 40px 0;
    }

    .title {
      font-size: 28px;
      font-weight: 600;
    }

    .sub_title {
      font-size: 18px;
      font-weight: 400;
    }
  }

  .referral {
    text-wrap: nowrap;
    font-size: 18px;
    font-weight: 300;
    letter-spacing: 0.78em;
    text-align: left;
    color: #ffffff;
    margin: 40px 0;
  }
}

.infoBox {
  color: #ffffff;
  position: absolute;
  bottom: 10px;
  font-size: 14px;
  z-index: 999;
}

.version {
  font-size: 14px;
}
</style>